package utils

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/mitchellh/mapstructure"
	"os"
	"path/filepath"
	"reflect"
	"ruoyi-go/framework/log"
)

func ParseMap(ctx *gin.Context) map[string]interface{} {
	var maps = make(map[string]interface{})

	return maps
}

func ReadLocalJson(name string) map[string]interface{} {

	dir, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	log.L.Info(dir)
	joinPath := filepath.Join(dir, "config")
	log.L.Info(joinPath)
	return DoReadJsonFile(filepath.Join(joinPath, name+".json"))
	//file, err := os.ReadFile(filepath.Join(joinPath, name+".json"))
	//if err != nil {
	//	panic(err)
	//}
	//err = json.Unmarshal(file, &maps)
	//if err != nil {
	//	panic(err)
	//}
	//return maps
}

func DoReadJsonFile(path string) map[string]interface{} {
	var maps = make(map[string]interface{})
	file, err := os.ReadFile(path)
	if err != nil {
		panic(err)
	}
	err = json.Unmarshal(file, &maps)
	if err != nil {
		panic(err)
	}
	return maps
}

func GetPostMap(ctx *gin.Context) (map[string]interface{}, error) {
	var maps = make(map[string]interface{})
	if err := ctx.ShouldBind(&maps); err != nil {
		return nil, err
	}
	return maps, nil
}

// Post struct
func GetPostStruct(ctx *gin.Context, p reflect.Type) (interface{}, error) {
	postMap, err := GetPostMap(ctx)
	if err != nil {
		panic(err)
	}
	tmp := reflect.New(p).Interface()
	res := mapstructure.Decode(postMap, tmp)
	return tmp, res
}
